package cn.initcap.concurrency.concurrency.lock;

import cn.initcap.concurrency.annoations.ThreadSafe;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import lombok.extern.slf4j.Slf4j;

/**
 * 使用J.U.C  ReentrantLock() 来保证线程安全
 *
 * @author initcap
 * @date Created in 2018/6/13 PM7:41.
 */
@ThreadSafe
@Slf4j
public class ReentrantReadWriteLockLock {

    private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();

    private final Map<String, Data> map = new TreeMap<>();

    private final Lock readLock = LOCK.readLock();

    private final Lock writeLock = LOCK.writeLock();

    public Data get(String key) {
        readLock.lock();
        try {
            return map.get(key);
        } finally {
            readLock.unlock();
        }
    }

    public Set<String> getAllKeys() {
        readLock.lock();
        try {
            return map.keySet();
        } finally {
            readLock.unlock();
        }
    }

    public Data put(String key, Data value) {
        writeLock.lock();
        try {
            return map.put(key, value);
        } finally {
            writeLock.unlock();
        }
    }

    private class Data {

    }

}
